<?php

class News_UI_Media
{
    var $Controller; 
    var $Library;
    function News_UI_Media($controller)
    {
        $this->Controller = $controller;
        if (isset($controller->Settings['delete']))
        {
            $id  = $controller->Settings['delete'];
            $grp = $controller->Settings['group'];
            $idx = "data/tube/{$grp}/{$id}.idx";
            $db  = "data/tube/{$grp}/{$id}.name";
            if (file_exists($db))
            {
                $path = $controller->Read($db);
                $jpeg = "{$path}.jpeg";
                unlink ($path);
                unlink ($jpeg);
	            if (!file_exists($path))
	            {
	                unlink($db);
	            } 
            }
            else if (file_exists($idx))
            {
	            $nfo    = simplexml_load_file($idx); 
                $result = $nfo->xpath ("//files/name");
                if ($result && sizeof($result) > 0)
                { 
                    foreach ($result as $old)
                    {
                        $url = "data/perm/{$grp}/{$id}/{$old}"; 
                        if (file_exists($url)) unlink ($url);
                    } 
                }
                
	            if (isset ($nfo->name) && file_exists($nfo->name))
	            {
		            unlink($nfo->name);
	            }
		        unlink($nfo->picture);
		        unlink($idx);
            }
            $uri = $this->Controller->URI (array('delete' => NULL, 'group'=> NULL));
            redirect ($uri); 
        }
        $this->Library = $this->GetLibrary();
    }
    
    function GetLibrary()
    {
        $dir       = 'data/tube/';
        $groupdirs = $this->Controller->OpenDir($dir); 
        $ret       = array();
        $lib       = array();
        for ($x=0;$x<sizeof($groupdirs);$x++)
        { 
            $name         = $groupdirs[$x]['name'];
            $path         = $groupdirs[$x]['path'];
            $lib[$name]   = $this->Controller->OpenDir ("{$path}/"); 
        }
        
        
        
        return $lib;
    }
    
    function Collate($extended = NULL)
    {
		$count = 0; $e=0; $ret=array();
        while (list($group, $value) = each ($this->Library))
        { 
            for ($i=0;$i<sizeof($value);$i++)
            {   
                $file = $value[$i]['name']; 
                $path = $value[$i]['path']; 
	            $arr  = explode ('.', $file);
	            $ext  = array_pop($arr);
	            $idx  = str_replace ('.name', '.idx', $path);
	            $data = NULL;
	            if ($ext == 'name')
	            {
	                if (file_exists($idx))
	                {
	                    unlink ($path);
	                    continue;
	                }
	                $name = trim($this->Controller->Read($path));
	                if (file_exists($name))
	                {
	                    $data  = $extended
	                           ? array ('id'=>array_pop($arr), 'name'=>$name, 'group'=>$group,
	                                    'subject'=>$name, 'duration'=>'UNKNOWN',
	                                    'picture'=>$name.'.jpeg')
	                           : $name;
	                } else unlink ($path);
	            }
	            else if ($ext=='idx')
	            {
                    $nfo  = simplexml_load_file($path);
                    if (file_exists($nfo->name))
                    {
	                    $data = $extended 
	                          ? array('id'=>"{$nfo->id}", 'name'=>"{$nfo->name}", 'group'=>$group,
	                                  'subject'=>"{$nfo->subject}", 'duration'=>"{$nfo->duration}",
	                                  'picture'=>"{$nfo->picture}")
	                          : $nfo->name;     
                    } else unlink ($path);
	            }
	            
	            if ($data)
	            {
	                $ret[] = $data;
	            }
            }
        }    
        
        if ($extended)
        {
	        for($x = 0; $x < sizeof($ret); $x++) {
			  for($y = 0; $y < sizeof($ret); $y++) {
			    if(strcmp($ret[$x]['subject'], $ret[$y]['subject']) < 0) {
			      $hold = $ret[$x];
			      $ret[$x] = $ret[$y];
			      $ret[$y] = $hold;
			    }
			  }
			}
        }
 
        

        return $ret;
    }
    
    function Display()
    {
//		echo "<html>" . 
//		     " <head>" . 
//		     "   <script language='javascript' src='/images.js?465'></script>" . 
//		     "   <script language='javascript' src='http://www.101stratford.com/101/ebp6/js/xmlextras.js'></script>" . 
//		     "   <link rel='stylesheet' href='/nntp.css?123' type='text/css'/>" . 
//		     " </head>" . 
//		     "<body onload='attach()'>";      

		$data               = array();
		$data['toolbar']    = $this->Controller->Factory->TabBar('Media');
        $data['header']     = "<a href='/ui/'>Home</a> &#187;";
        $data['main']       = '';
		$page  = $this->Controller->Settings['page'];
	    if (strlen($page) == 0) $page = 1;
		$blank = "http://www.101stratford.com/webservices/images/clear.gif";

		if (isset($this->Controller->Settings['group']))
		{    
		    $group = $this->Controller->Settings['group'];  
		    $id    = $this->Controller->Settings['id'];
		    $db    = "data/tube/{$group}/{$id}.name";
		    $find  = $this->Controller->URI (array('ui'      => 'articlefinder',
                                                   'pic'     => $id));
		    $bfind = $this->Controller->Factory->Button ($find, 'Find in ' . $group, 'i.p.cont.individual.gif'); 
		    
            $idx   = "data/tube/{$group}/{$id}.idx"; 
            $msg   = $m4v;
            if (file_exists($idx))
            {
                $nfo  = simplexml_load_file($idx); 
                $msg  = $nfo->subject;
                $m4v  = $nfo->name;
            }
            else
            {
		        $m4v   = trim($this->Controller->Read($db)); 
            }
                    
            $uri   = $this->Controller->URI (array('group'=>NULL, 'id'=>NULL));                
            $data['header'] .= " <a href='{$uri}'>Media</a> &#187; " . 
		                       "<a href='/ui/commandhandler/request/group/group/{$group}'>{$group}</a> &#187; {$msg}"; 
		    
//		    $data['header'] .= "<div style='float:right'>$bfind </div>";   
		    
            $data['main'] .= "<center>" . $this->Controller->Factory->VideoPlayer($m4v, 640, 480) . "<div>{$msg}</div></center>"; 
            
            echo $this->Controller->Structure ($data); 
            return;               
		    
		}
    
		$num    = $page * UI_PAGE_SIZE;
		$min    = $num - UI_PAGE_SIZE;  
		$result = $this->Collate (true); 
        
        $data['header']    .= " Media"; 
        $data['controlbar'] = $this->Controller->Factory->Paginator(sizeof ($result), array('ui'=>'media', 'page'=>NULL));
        
		
		for($x=$min;$x<$num&&$x<sizeof($result);$x++)
		{
		    $jpeg = $result[$x]['picture'];
		    $grp  = $result[$x]['group'];
		    $key  = $result[$x]['id'];
		    $dur  = $result[$x]['duration'];
            $ax   = $this->Controller->URI(array('delete' => $key, 'group' => $grp));  
            $edit = $this->Controller->Factory->Button ($ax, 'Delete', '/images/i.p.delete.gif', "Are you sure you want to delete this media file?");
            $uri  = $this->Controller->URI(array('group' => $grp, 'id'    => $key));  
            $go   = "/ui/commandhandler/request/group/group/{$grp}";
		    $msg  = $edit . ' Duration: ' . $dur . '<div align="center"><a href="'.$go.'"><b>' . $grp . '</b></a></div>' . $result[$x]['subject'];
		    $data['main'] .= $this->Controller->Factory->Thumbnail ("/{$jpeg}", $uri, $msg); 
		}
		echo $this->Controller->Structure ($data); 
		return;
		 
    }
}